import argparse
from datetime import datetime, timedelta
import pymysql
from configparser import ConfigParser
import codecs
import os

CONFIG_FILE = "config.ini"

def read_mysql_config():
    config = ConfigParser()
    config.read_file(codecs.open(CONFIG_FILE, 'r', encoding='utf-8-sig'))
    return {
        'host': config.get("mysql", "host"),
        'user': config.get("mysql", "user"),
        'password': config.get("mysql", "password"),
        'database': config.get("mysql", "database")
    }

def create_mysql_connection(cfg):
    return pymysql.connect(
        host=cfg['host'],
        user=cfg['user'],
        password=cfg['password'],
        database=cfg['database'],
        charset='utf8mb4'
    )

def get_logged_dates(connection, repo, branch, start_date, end_date):
    sql = """
        SELECT DISTINCT date_param
        FROM gitee_logs
        WHERE repo = %s AND branch = %s AND date_param BETWEEN %s AND %s
    """
    with connection.cursor() as cursor:
        cursor.execute(sql, (repo, branch, start_date, end_date))
        rows = cursor.fetchall()
        return {row[0] for row in rows}

def generate_command(date_str, repo, branch):
    return f"python3 gitee_review.py -d {date_str} -p {repo} -b {branch}"

def main():
    parser = argparse.ArgumentParser(description="Check missing Gitee stats runs and generate recovery script")
    parser.add_argument('--start', required=True, help='Start date YYYY-MM-DD')
    parser.add_argument('--end', required=True, help='End date YYYY-MM-DD')
    parser.add_argument('--repo', required=True, help='Repositories (comma-separated)')
    parser.add_argument('--branch', required=True, help='Branches (comma-separated)')
    parser.add_argument('--out', default='run_missing.sh', help='Output shell script file')
    args = parser.parse_args()

    mysql_cfg = read_mysql_config()
    conn = create_mysql_connection(mysql_cfg)

    start_date = datetime.strptime(args.start, "%Y-%m-%d").date()
    end_date = datetime.strptime(args.end, "%Y-%m-%d").date()
    all_dates = {start_date + timedelta(days=i) for i in range((end_date - start_date).days + 1)}

    repos = [r.strip() for r in args.repo.split(',')]
    branches = [b.strip() for b in args.branch.split(',')]

    missing_total = 0
    with open(args.out, "w", encoding="utf-8") as f:
        f.write("#!/bin/bash\n\n")
        for repo in repos:
            for branch in branches:
                logged_dates = get_logged_dates(conn, repo, branch, start_date, end_date)
                missing_dates = sorted(all_dates - logged_dates)

                if missing_dates:
                    print(f"❗ {repo} / {branch} — {len(missing_dates)} missing")
                    for d in missing_dates:
                        cmd = generate_command(d.isoformat(), repo, branch)
                        f.write(cmd + "\n")
                        print(" ", cmd)
                    missing_total += len(missing_dates)
                else:
                    print(f"✅ {repo} / {branch} — OK")

    conn.close()

    # Сделать .sh-файл исполняемым
    os.chmod(args.out, 0o755)

    print(f"\n✅ Recovery script written to: {args.out}")
    if missing_total == 0:
        print("No missing days — all done.")
    else:
        print(f"{missing_total} missing executions found. Use the script to recover.")

if __name__ == "__main__":
    main()
